<?php
declare (strict_types = 1);

namespace app\controller\backend;

use app\exception\ModelEmptyException;
use app\exception\ModelException;
use app\model\Theme;
use app\model\ThemeFile;
use app\service\ThemeService;
use app\validate\ThemeValidate;
use think\exception\ValidateException;
use think\facade\Db;
use think\response\Json;


class ThemeController extends BaseController
{
    /**
     * 已安装模板
     *
     * @return Json
     * @throws ModelException
     */
    public function index(Theme $theme): Json
    {
        $website_id = (int)input('param.website_id');
        if(!$website_id){
            return jsonReturn(-1,'网站ID不能为空');
        }
        $lang = input('param.lang') ?: 'zh';
        $where = [
            ['seller_id','=',$this->admin['seller_id']],
            ['website_id','=',$website_id],
            ['lang','=',$lang]
        ];

        $limit = $this->setLimit();
        $themeList = $theme->getThemeList($where,$limit);
        return json(pageReturn($themeList));
    }

    /**
     * 模板完整更新
     *
     * @return Json
     * @throws ModelException*@throws \app\exception\ModelEmptyException
     * @throws ModelEmptyException
     */
    public function update(ThemeService $themeService): Json
    {
        if(request()->isPost()){
            $param = input('post.');
            try {
                validate(ThemeValidate::class)->scene('update')->check($param);
            } catch (ValidateException $e) {
                return jsonReturn(-1, $e->getError());
            }
            $suffix = config('view.view_suffix');

            return $themeService -> updateTheme($param['theme_id'],$param['website_id'],$this->admin['seller_id'],$suffix);
        }
        return jsonReturn(-3,'请求方法错误');
    }

    /**
     * 系统模版
     *
     * @param Theme $themeModel
     * @return Json
     */
    public function install(Theme $themeModel): Json
    {
        $themesDirs = hcScanDir("themes/hc_original/*", GLOB_ONLYDIR);
        $themes = [];
        foreach ($themesDirs as $dir) {
            $manifest = "themes/hc_original/$dir/manifest.json";
            if (hcFileExist($manifest)) {
                $manifest       = file_get_contents($manifest);
                $theme          = json_decode($manifest, true);
            }
            $theme['theme'] = $dir;
            array_push($themes, $theme);
        }
        return jsonReturn(0,'success',$themes);
    }

    /**
     * 模版安装
     *
     * @throws ModelException
     */
    public function installTheme(ThemeService $service): Json
    {
        if ($this->request->isPost()) {
            set_time_limit(300);
            $param = input('post.');
            try {
                validate(ThemeValidate::class)->scene('installTheme')->check($param);
            }catch (ValidateException $e){
                return jsonReturn(-1,$e->getError());
            }
            $suffix = config('view.view_suffix');
            return $service->installTheme($param['theme'],$param['website_id'],$this->admin['seller_id'],$suffix,$param['lang']);
        }
        return jsonReturn('-3','访问方法错误');
    }

    /**
     * 卸载模板
     * @throws ModelEmptyException
     * @throws ModelException
     */
    public function uninstall(ThemeService $service): Json
    {
        if ($this->request->isPost()) {
            $param = input('post.');
            try {
                validate(ThemeValidate::class)->scene('uninstall')->check($param);
            }catch (ValidateException $e){
                return jsonReturn(-1,$e->getError());
            }
            return $service->uninstallTheme($param['theme_id'],$param['website_id'],$this->admin['seller_id']);
        }
        return jsonReturn('-3','访问方法错误');
    }

    /**
     * 模板文件
     *
     * @throws ModelException
     */
    public function tmpFile(ThemeFile $ThemeFile): Json
    {
        $param = input('param.');
        try {
            validate(ThemeValidate::class)->scene('tmpFile')->check($param);
        } catch (ValidateException $e) {
            return jsonReturn(-1, $e->getError());
        }
        $limit = $this->setLimit();
        $where = [
            'seller_id' => $this->admin['seller_id'],
            'theme_id'  => $param['theme_id'],
            'website_id'    => $param['website_id'],
        ];
        $res = $ThemeFile -> getThemeFileList($where,'id,name,file,description,action',$limit);
        return json(pageReturn($res));
    }

    /**
     *
     * @param ThemeFile $ThemeFile
     * @return Json
     * @throws ModelException
     */
    public function templateFile(ThemeFile $ThemeFile): Json
    {
        $param = input('param.');
        try {
            validate(ThemeValidate::class)->scene('templateFile')->check($param);
        } catch (ValidateException $e) {
            return jsonReturn(-1, $e->getError());
        }
        $theme = new Theme();
        $activeTheme = $theme->getActiveTheme(['seller_id'=>$this->admin['seller_id'],'website_id'=>$param['website_id'],'is_active'=>1])['data'];
        if(empty($activeTheme)){
            return jsonReturn(-1,'未启用模版');
        }
        $where = [
            'seller_id' => $this->admin['seller_id'],
            'theme_id'  => $activeTheme['id'],
            'website_id'    => $param['website_id'],
        ];
        $template = $ThemeFile -> getAllCustomData($where)['data'];
        $data = [];
        foreach ($template as $val){
            $file = basename($val['file']);
            if($param['type'] == 1){
                if(preg_match('/^list_/',$file) || $file == 'index'){
                    array_push($data,$val);
                }
            }else if($param['type'] == 2){
                if(preg_match('/^detail/',$file)){
                    array_push($data,$val);
                }
            }else if($param['type'] == 3){
                if(preg_match('/^single_/',$file) || $file == 'index'){
                    array_push($data,$val);
                }
            }else{
                array_push($data,$val);
            }
        }
        return jsonReturn(0,'success',$data);
    }

    /**
     * 启用模版
     *
     * @throws ModelException
     */
    public function active(Theme $Theme): Json
    {
        if(request()->isPost()){
            $param = input('post.');
            try {
                validate(ThemeValidate::class)->scene('active')->check($param);
            } catch (ValidateException $e) {
                return jsonReturn(-1, $e->getError());
            }
            Db::startTrans();
            try{
                // 将所有模版暂停启用
                $Theme->updateTheme(['seller_id'=>$this->admin['seller_id'],'website_id'=>$param['website_id'],'lang'=>$param['lang']],['is_active'=>2]);
                // 启用当前模版
                $res = $Theme->updateTheme(['id'=>$param['theme_id'],'seller_id'=>$this->admin['seller_id'],'website_id'=>$param['website_id'],'lang'=>$param['lang']],['is_active'=>1]);
                Db::commit();
            }catch (\Exception $e){
                Db::rollback();
                return jsonReturn(-3,'模版安装启用错误');
            }
            return json($res);
        }
        return jsonReturn(-3,'请求方法错误');
    }

    /**
     * 所有目录
     * @throws ModelEmptyException
     * @throws ModelException
     */
    public function allFilePath(ThemeService $service): Json
    {
        $param = input('param.');
        try {
            validate(ThemeValidate::class)->scene('allFilePath')->check($param);
        }catch (ValidateException $e){
            return jsonReturn(-1,$e->getError());
        }
        return $service->filesPath($param['website_id'],$param['lang']);
    }

    public function allFiles(ThemeService $service): Json
    {
        $param = input('param.');
        try {
            validate(ThemeValidate::class)->scene('allFiles')->check($param);
        }catch (ValidateException $e){
            return jsonReturn(-1,$e->getError());
        }
        return $service->files($param['path'],(int)$param['website_id'],$param['lang']);
    }

    public function dealWithImg(): Json
    {
        $sourcePath = input('post.source');
        $terminalPath = input('post.terminal');

        $sourceFiles = glob($sourcePath.'/*');

        $tmpFiles = [];
        foreach ($sourceFiles as $sourceFile) {
            $key = pathinfo($sourceFile,PATHINFO_FILENAME);
            $ext = pathinfo($sourceFile,PATHINFO_EXTENSION);
            $tmpFiles[$key] = $ext;
        }
        $terminalFiles = glob($terminalPath.'/*');
        $termFiles = [];
        foreach ($terminalFiles as $val) {
            $key = pathinfo($val,PATHINFO_FILENAME);
            $ext = pathinfo($val,PATHINFO_EXTENSION);
            $termFiles[$key] = $ext;
        }
        foreach ($termFiles as $key => $term){
            if($term != $tmpFiles[$key]){
                $formName = $terminalPath .'/' . $key . '.' . $term;
                $toName = $terminalPath.'/' . $key . '.' . $tmpFiles[$key];
                rename($formName,$toName);
            }
        }
        return jsonReturn(0,'success');
    }

    public function delete(ThemeService $service): Json
    {
        $theme = input('param.theme');
        if(empty($theme)){
            return jsonReturn(-1,'模版名称不能为空');
        }
        $res = $service -> delOriginalTheme($theme);
        return json($res);
    }
}
